package com.xuzao.developer.utils;

import org.jasypt.encryption.pbe.StandardPBEStringEncryptor;
import org.jasypt.encryption.pbe.config.EnvironmentPBEConfig;

/**
 * @author xuzao
 * @description
 * @date 2019-08-26 15:03
 */

public class JasyptUtil {
    private static String salt = System.getProperty("salt");
    /**
     * 加密
     * @param plainText
     * @return
     * @throws Exception
     */
    public static String encrypt(String plainText){
        StandardPBEStringEncryptor standardPBEStringEncryptor = new StandardPBEStringEncryptor();
        EnvironmentPBEConfig config = getConfig();
        standardPBEStringEncryptor.setConfig(config);
        //明文密码
        String encryptedText = standardPBEStringEncryptor.encrypt(plainText);
        //密文密码
        return encryptedText;
    }

    /**
     * 解密
     * @param encryptedText
     * @return
     * @throws Exception
     */
    public static String decrypt(String encryptedText){
        StandardPBEStringEncryptor standardPBEStringEncryptor = new StandardPBEStringEncryptor();
        EnvironmentPBEConfig config = getConfig();
        standardPBEStringEncryptor.setConfig(config);
        //密文密码
        String plainText = standardPBEStringEncryptor.decrypt(encryptedText);
        //明文密码
        return plainText;
    }


    public static EnvironmentPBEConfig getConfig(){
        EnvironmentPBEConfig config = new EnvironmentPBEConfig();
        //实现方式（固定）
        config.setAlgorithm("PBEWithMD5AndDES");
        //解密所需密码（盐）（与加密保持一致）
        config.setPassword(salt);
        return config;
    }
}
